package com.group1.bookmanagement.service.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.stereotype.Service;

import com.group1.bookmanagement.dao.BaseDao;
import com.group1.bookmanagement.domain.Book;
import com.group1.bookmanagement.domain.Label;
import com.group1.bookmanagement.domain.PageBean;
import com.group1.bookmanagement.domain.Photo;
import com.group1.bookmanagement.domain.User;
import com.group1.bookmanagement.service.BookService;
import com.group1.bookmanagement.util.MailUtils;

@Service("bookService")
public class BookServiceImpl implements BookService {
	
	@Resource(name = "baseDao")
	private BaseDao<Book> bookDao;
	@Resource(name = "baseDao")
	private BaseDao<Photo> photoDao;
	@Resource(name = "pageBean")
	private PageBean<Book> pageBean;

	@Override
	public void saveBook(Book book) {
		Date date = new Date();
		book.setCreatedAt(date);
		book.setUpdatedAt(date);
		bookDao.save(book);
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				Label label = book.getLabel();
				Set<User> users = label.getUsers();
				Iterator<User> iterator = users.iterator();
				while (iterator.hasNext()) {
					User user = iterator.next();
					if (user.getEmail() != null && user.getEmail().equals("")) {
						MailUtils.sendMail(user.getEmail(), "通知", "明天大扫除");
					}
				}
			}
		}).start();
	}

	@Override
	public void deleteBook(Book book) {
		Photo cover = book.getCover();
		if (cover != null) {
			cover.getFile().delete();
		}
		bookDao.delete(book);
	}

	@Override
	public void updateBook(Book book) {
		//原封面
		Photo cover_previous = getBook(book.getId()).getCover();
		//修改后的封面
		Photo cover = book.getCover();
		
		if (cover == null) {
			book.setCover(cover_previous);
		} else {
			photoDao.save(cover);
		}
		
		Session session = bookDao.openSession();
		session.beginTransaction();
		String hql = new StringBuilder("update Book b set ")
				.append("b.bookName = ?, ")
				.append("b.cover = ?, ")
				.append("b.introduction = ?, ")
				.append("b.authorName = ?, ")
				.append("b.press = ?, ")
				.append("b.publicationDate = ?, ")
				.append("b.price = ?, ")
				.append("b.stockQuantity = ?, ")
				.append("b.updatedAt = ? ")
				.append("where id = ?")
				.toString();
		
		Query query = session.createQuery(hql);
		query.setParameter(0, book.getBookName());
		query.setParameter(1, book.getCover());
		query.setParameter(2, book.getIntroduction());
		query.setParameter(3, book.getAuthorName());
		query.setParameter(4, book.getPress());
		query.setParameter(5, book.getPublicationDate());
		query.setParameter(6, book.getPrice());
		query.setParameter(7, book.getStockQuantity());
		query.setParameter(8, new Date());
		query.setParameter(9, book.getId());
		query.executeUpdate();
		session.getTransaction().commit();
		session.close();
		
		if (cover != null && cover_previous != null) {
			boolean equals = cover_previous.equals(cover);
			if (!equals) {//如果修改则删除原来的封面
				cover_previous.getFile().delete();
				photoDao.delete(cover_previous);
			}
		}
	}

	@Override
	public Book getBook(Integer id) {
		return bookDao.get(Book.class, id);
	}

	@Override
	public PageBean<Book> listBook(Integer page) {
		pageBean.setHql("from Book");
		pageBean.setPage(page);
		return pageBean;
	}
	
	@Override
	public PageBean<Book> listByLabel(Label label, Integer page) {
		pageBean.setHql("from Book b where b.label=?");
		pageBean.setParam(label);
		pageBean.setPage(1);
		pageBean.query();
		return pageBean;
	}
	
	@Override
	public List<Book> top(Integer limit, String property, String order) {
		if (property == null) {
			property = "id";
		}
		
		if (order == null) {
			order = "asc";
		}
		
		String hql = new StringBuilder("from Book b Order by b.")
				.append(property)
				.append(" ")
				.append(order)
				.toString();
		return bookDao.findAll(hql, 0, limit);
	}
	
	public List<Book> listBook(User user) {
		String hql = "from Book b where b.label in(:labels)";
		Session session = bookDao.openSession();
		session.beginTransaction();
		
		Query query = session.createQuery(hql);
		query.setParameterList("labels", user.getLabels());
		List list = query.list();
		
		session.getTransaction().commit();
		session.close();
		return list;
	}
	
}
